<template>
  <draw-component
    :drawer-visible="state.show"
    size="650px"
    title="新增/编辑用户"
    @close-drawer="handleClose"
    @save-drawer="handleSubmit"
  >
    <el-form
      ref="formRef"
      :model="state.formData"
      :rules="state.formRules"
      label-width="90px"
      class="my-form-box2"
    >
      <div class="df aic jcsb">
        <el-form-item label="用户工号:" prop="employeeId">
          <el-input v-model="state.formData.employeeId" placeholder="请输入用户工号"></el-input>
        </el-form-item>
        <el-form-item label="区域编码:" prop="areaCode">
          <el-select v-model="state.formData.areaCode" placeholder="请选择区域">
            <el-option
              v-for="item in areaCodeList"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="df aic jcsb">
        <el-form-item label="用户类型:" prop="userType">
          <el-select v-model="state.formData.userType" placeholder="请选择用户类型">
            <el-option
              v-for="item in userTypeList"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名:" prop="userName">
          <el-input v-model="state.formData.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
      </div>
      <div class="df aic jcsb">
        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="state.formData.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="用户状态:" prop="status">
          <el-select v-model="state.formData.status" placeholder="请选择用户状态">
            <el-option
              v-for="item in userStatusDics"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="df aic jcsb">
        <el-form-item label="职称:" prop="professionalTitles">
          <el-select v-model="state.formData.professionalTitles" placeholder="请选择职称">
            <el-option
              v-for="item in professionalTitlesList"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门:" prop="department">
          <el-select v-model="state.formData.department" placeholder="请选择部门">
            <el-option
              v-for="item in departmentList"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="有效期类型:" prop="validityType">
        <el-radio-group v-model="state.formData.validityType">
          <el-radio v-for="(item, index) in validityTypeDics" :key="index" :label="item.code">{{
            item.name
          }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <div v-if="state.formData.validityType == '0'" class="form-date-box df aic">
        <el-form-item
          label="有效期:"
          prop="beginTime"
          :rules="[
            {
              required: state.formData.validityType === '0' ? true : false,
              message: '请选择开始有效期',
              trigger: 'blur'
            }
          ]"
        >
          <el-date-picker
            v-model="state.formData.beginTime"
            type="date"
            :disabled-date="disableDateFunc"
            placeholder="开始有效期"
            :clearable="false"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <div class="date-line">-</div>
        <el-form-item
          prop="endTime"
          label-width="0px"
          :rules="[
            {
              required: state.formData.validityType === '0' ? true : false,
              message: '请选择结束有效期',
              trigger: 'blur'
            }
          ]"
        >
          <el-date-picker
            v-model="state.formData.endTime"
            type="date"
            :clearable="false"
            :disabled-date="disableEndDateFunc"
            placeholder="结束有效期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </div>
    </el-form>
    <table-page-content
      ref="tableRef"
      :table-data="state.roleList"
      :table-headers="state.tableHeader"
      :table-height="'50vh'"
      :is-pager="false"
      :is-slot-num="false"
      :is-selection="true"
    >
    </table-page-content>
  </draw-component>
</template>

<script lang="ts" setup>
import { PropType } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { vlidateUser, validatePhone } from '@/utils/validate'
import { userStatusDics, validityTypeDics } from '@/hooks/dicsData'
import { useProxy } from '@/utils/proxy'
import { validatePhoneExist, validateCodeExist, addSubmit, editSubmit, getDetailById } from '../api'
import { getRoleAllList } from '@/views/userManagement/role/api'
const valPhoneExist = async (rule: any, value: any, callback: any) => {
  if (!value) return callback()
  const { data } = await validatePhoneExist<boolean>({
    phone: value,
    userId: state.userId || null
  })
  if (!data) {
    callback(new Error('手机号重复'))
  } else {
    callback()
  }
}
const valCodeExist = async (rule: any, value: any, callback: any) => {
  if (!value) return callback()
  const { data } = await validateCodeExist<boolean>({
    employeeId: value,
    userId: state.userId || null
  })
  if (!data) {
    callback(new Error('用户工号重复'))
  } else {
    callback()
  }
}
const props = defineProps({
  areaCodeList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  userTypeList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  departmentList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  professionalTitlesList: {
    type: Array as PropType<any[]>,
    default: () => []
  }
})
const emit = defineEmits(['handleAdded'])
const { proxy } = useProxy()
const formRef = ref<FormInstance>()
const tableRef = ref()
const state = reactive({
  collapse: true,
  userId: '',
  show: false,
  isSubmiting: false,
  roleList: [],
  tableHeader: [{ key: 'roleName', name: '角色名称' }],
  formData: {
    employeeId: '',
    areaCode: '',
    userType: '',
    userName: '',
    phone: '',
    status: '1',
    professionalTitles: '',
    department: '',
    validityType: '1',
    beginTime: '',
    endTime: ''
  },
  formRules: {
    employeeId: [
      { validator: valCodeExist, trigger: 'blur' },
      { validator: vlidateUser, trigger: 'blur' }
    ],
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { max: 64, message: '输入字符不得超过64位', trigger: 'blur' }
    ],
    userType: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
    areaCode: [{ required: true, message: '请选择区域编码', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' },
      { validator: valPhoneExist, trigger: 'blur' }
    ],
    status: [{ required: true, message: '请选择用户状态', trigger: 'blur' }]
  } as FormRules,
  permissionOptions: [],
  props: {
    label: 'name',
    children: 'permissions'
  }
})
// 关闭回调
const handleClose = () => {
  state.userId = ''
  state.formData = {
    employeeId: '',
    areaCode: '',
    userType: '',
    userName: '',
    phone: '',
    status: '1',
    professionalTitles: '',
    department: '',
    validityType: '1',
    beginTime: '',
    endTime: ''
  }
  state.show = false
}
// 设置时间不可选项
const disableDateFunc = (time: Date) => {
  return time.getTime() > Date.parse(state.formData.endTime || '')
}

const disableEndDateFunc = (time: Date) => {
  return time.getTime() < Date.parse(state.formData.beginTime || '')
}
// 获取详情
const getRoleDetail = async () => {
  let { data } = await getDetailById<any>(state.userId)
  const form = {} as any
  Object.keys(state.formData).forEach((item, index) => {
    form[item] = data[item] ?? ''
  })
  state.formData = form
  nextTick(() => {
    state.roleList.forEach((item: any) => {
      if (data.roles.some((v: any) => item.roleId == v.roleId && v.belongToThisUser)) {
        tableRef.value.toggleRowSelection(item, true)
      }
    })
  })
}
// 获取角色列表
const getList = () => {
  state.roleList = []
  getRoleAllList<any>().then((res) => {
    state.roleList = res.data
  })
}
// 保存
const handleSubmit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      if (state.isSubmiting) return
      state.isSubmiting = true
      const params = { ...state.formData } as any
      let selectItem = tableRef.value.getAllSelectItem()
      if (selectItem.length > 0) {
        params.roleIds = selectItem.map((v: any) => v.roleId)
      } else {
        params.roleIds = []
      }
      if (state.userId) {
        editSubmit(state.userId, params)
          .then(() => {
            proxy.$message.msgSuccess('编辑成功')
            state.isSubmiting = false
            handleClose()
            emit('handleAdded')
          })
          .catch(() => {
            state.isSubmiting = false
          })
      } else {
        addSubmit(params)
          .then(() => {
            proxy.$message.msgSuccess('新增成功')
            state.isSubmiting = false
            handleClose()
            emit('handleAdded')
          })
          .catch(() => {
            state.isSubmiting = false
          })
      }
    }
  })
}
getList()
defineExpose({ state, getRoleDetail })
</script>

<style lang="scss" scoped></style>
